<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="合同编号" prop="contNo">
        <el-input
          v-model="queryParams.contNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请购单编号" prop="reqNo">
        <el-input
          v-model="queryParams.reqNo"
          placeholder="请输入请购单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="工厂下单单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入工厂下单单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商id" prop="suppId">
        <el-input
          v-model="queryParams.suppId"
          placeholder="请输入供应商id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pur:purchasesum:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pur:purchasesum:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pur:purchasesum:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['pur:purchasesum:importData']"
        >导入</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pur:purchasesum:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="purchasesumList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" align="center" prop="contNo" width="150" />

      <el-table-column label="请购单编号" align="center" prop="reqNo" width="120" />

      <el-table-column label="下发时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="需求时间" align="center" prop="demandTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.demandTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="工厂下单单号" align="center" prop="orderNo" width="120" />

      <el-table-column label="采购合同编号" align="center" prop="purcontNo" width="120" />

      <el-table-column label="供应商名称" align="center" prop="suppName" width="120" />

      <el-table-column label="请购类别" align="center" prop="reqType" show-overflow-tooltip />

      <el-table-column label="物料描述" align="center" prop="mateDesc" width="120" show-overflow-tooltip />

      <!-- <el-table-column label="物料代码" align="center" prop="mateCode" /> -->

      <el-table-column label="数量" align="center" prop="num" />

      <el-table-column label="数量单位" align="center" prop="numUnit" />

      <el-table-column label="面积(m2)" align="center" prop="area" />

      <el-table-column label="重量(KG)" align="center" prop="weight" />

      <el-table-column label="采购合同单价" align="center" prop="purcontUnitfee" width="120" />

      <el-table-column label="采购合同金额" align="center" prop="purcontFee" width="120" />

      <el-table-column label="采购代码" align="center" prop="purCode" />

      <el-table-column label="到货状态" align="center" prop="revState" />

      <el-table-column label="到货数量" align="center" prop="revNum" />

      <el-table-column label="到货时间" align="center" prop="revTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.revTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="收货单签收" align="center" prop="revSign" width="120" />

      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['pur:purchase:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDisable(scope.row)"
            v-hasPermi="['pur:purchase:disable']">禁用</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDisable(scope.row)"
            v-hasPermi="['pur:purchase:disable']">启用</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['pur:purchase:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购信息总对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同编号" prop="contNo">
          <el-input v-model="form.contNo" placeholder="请输入合同编号" disabled="true" />
        </el-form-item>
        <el-form-item label="请购单编号" prop="reqNo">
          <el-input v-model="form.reqNo" placeholder="请输入请购单编号" disabled="true" />
        </el-form-item>
        <el-form-item label="需求时间" prop="demandTime">
          <el-date-picker clearable
            v-model="form.demandTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择需求时间" disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下发时间" prop="sendTime">
          <el-date-picker clearable
            v-model="form.sendTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择下发时间" disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物料描述" prop="mateDesc">
          <el-input v-model="form.mateDesc" placeholder="请输入物料描述" disabled="true" />
        </el-form-item>
        <el-form-item label="物料代码" prop="mateCode">
          <el-input v-model="form.mateCode" placeholder="请输入物料代码" disabled="true" />
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入数量" disabled="true" />
        </el-form-item>
        <el-form-item label="数量单位" prop="numUnit">
          <el-input v-model="form.numUnit" placeholder="请输入数量单位" disabled="true" />
        </el-form-item>
        <el-form-item label="重量(KG)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量(KG)" disabled="true" />
        </el-form-item>
        <el-form-item label="面积(m2)" prop="area">
          <el-input v-model="form.area" placeholder="请输入面积(m2)" disabled="true" />
        </el-form-item>
        <el-form-item label="处理方式" prop="dealMethod">
          <el-input v-model="form.dealMethod" placeholder="请输入处理方式" disabled="true" />
        </el-form-item>
        <el-form-item label="发货地点" prop="sendPlace">
          <el-input v-model="form.sendPlace" placeholder="请输入发货地点" disabled="true" />
        </el-form-item>
        <el-form-item label="工厂下单单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入工厂下单单号" disabled="true" />
        </el-form-item>
        <el-form-item label="采购合同编号" prop="purcontNo">
          <el-input v-model="form.purcontNo" placeholder="请输入采购合同编号" disabled="true" />
        </el-form-item>
        <el-form-item label="供应商id" prop="suppId">
          <el-input v-model="form.suppId" placeholder="请输入供应商id" disabled="true" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="suppName">
          <el-input v-model="form.suppName" placeholder="请输入供应商名称" disabled="true" />
        </el-form-item>
        <el-form-item label="采购合同单价" prop="purcontUnitfee">
          <el-input v-model="form.purcontUnitfee" placeholder="请输入采购合同单价" disabled="true" />
        </el-form-item>
        <el-form-item label="采购合同金额" prop="purcontFee">
          <el-input v-model="form.purcontFee" placeholder="请输入采购合同金额" disabled="true" />
        </el-form-item>
        <el-form-item label="采购代码" prop="purCode">
          <el-input v-model="form.purCode" placeholder="请输入采购代码" disabled="true" />
        </el-form-item>
        <el-form-item label="到货状态" prop="revState">
          <el-input v-model="form.revState" placeholder="请输入到货状态" disabled="true" />
        </el-form-item>
        <el-form-item label="到货数量" prop="revNum">
          <el-input v-model="form.revNum" placeholder="请输入到货数量" disabled="true" />
        </el-form-item>
        <el-form-item label="到货时间" prop="revTime">
          <el-date-picker clearable
            v-model="form.revTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择到货时间" disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收货单签收" prop="revSign">
          <el-input v-model="form.revSign" placeholder="请输入收货单签收" disabled="true" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled="true" />
        </el-form-item>
        <el-form-item label="附件" prop="fileUrl">
          <el-input v-model="form.fileUrl" placeholder="请输入附件" disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 采购信息总导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                action=""
                :http-request="importData"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :auto-upload="false"
                drag
        >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的采购信息总数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
      </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchasesum, getPurchasesum, delPurchasesum, addPurchasesum, updatePurchasesum, disablePurchasesum  } from "@/api/pur/purchasesum";
import { getToken } from "@/utils/auth";
import { downBlobFile } from "@/utils/ruoyi";
import axios from 'axios';

export default {
  name: "Purchasesum",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购信息总表格数据
      purchasesumList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contNo: null,
        reqNo: null,
        reqType: null,
        orderNo: null,
        suppId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 用户导入参数
      upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的客户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/pur/purchasesum/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购信息总列表 */
    getList() {
      this.loading = true;
      listPurchasesum(this.queryParams).then(response => {
        this.purchasesumList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contNo: null,
        reqNo: null,
        demandTime: null,
        sendTime: null,
        reqType: null,
        mateDesc: null,
        mateCode: null,
        num: null,
        numUnit: null,
        weight: null,
        area: null,
        dealMethod: null,
        sendPlace: null,
        orderNo: null,
        purcontNo: null,
        suppId: null,
        suppName: null,
        purcontUnitfee: null,
        purcontFee: null,
        purCode: null,
        revState: null,
        revNum: null,
        revTime: null,
        revSign: null,
        remark: null,
        isDel: null,
        status: null,
        createTime: null,
        createId: null,
        createName: null,
        modifyTime: null,
        modifyId: null,
        fileUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getPurchasesum(id).then(response => {
        this.open = true;
        this.title = "添加采购信息总";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchasesum(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购信息总";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchasesum(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchasesum(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购信息总编号为"' + ids + '"的数据项？').then(function() {
        return delPurchasesum(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pur/purchasesum/export', {
        ...this.queryParams
      }, `采购信息总_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
        this.upload.title = "客户导入";
        this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
        this.download('erp/customer/importTemplate', {
        }, `采购信息总_template_${new Date().getTime()}.xlsx`)
    },
    importData(file) {
        const loading = this.$loading({
            lock: true,
            text: '数据导入中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        let formData = new FormData();
        formData.append('file', file.file);
        return axios.post(this.upload.url + '?updateSupport=' + this.upload.updateSupport, formData, {
            headers: this.upload.headers,
            responseType: 'blob'
        }).then(res => {
            loading.close()
            this.handleFileSuccess(res,file);
        }).catch(err => {
            loading.close()
        })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(res.data.type === 'application/json') {
            let reader = new FileReader()
            reader.readAsText(res.data);
            reader.onloadend= ()=> {
                let rsp = JSON.parse(reader.result);
                if(rsp.code == 200){
                    this.$modal.msgSuccess(rsp.msg);
                    this.getList();
                } else {
                    this.$modal.msgError(rsp.msg);
                }
            }
        } else {
            this.$modal.msgError("导入错误,请查看回执文件");
            let fileName = file.file.name;
            if (fileName.lastIndexOf(".xls") == fileName.length - 4 ){
                fileName =  fileName.substring(0, fileName.lastIndexOf(".xls"))
            } else if(fileName.lastIndexOf(".xlsx") == fileName.length - 5) {
                fileName =  fileName.substring(0, fileName.lastIndexOf(".xlsx"))
            }
            downBlobFile(downBlobFile(res.data,fileName+"Back.xlsx"));
        }
    },
    // 提交上传文件
    submitFileForm() {
        this.$refs.upload.submit();
    }
  }
};
</script>
